﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Q7.BevTree
{
    public class BevNodeTerminal : BevNode
    {
        private int _status = STA_READY;
        private bool _needExit;

        public const int STA_READY = 0;
        public const int STA_RUNNING = 1;
        public const int STA_FINISH = 2;

        public BevNodeTerminal(string debugName)
            : base(debugName)
        {
        }

        protected override int DoTick(BevNodeInputParam input, BevNodeOutputParam output)
        {
            var isFinish = BRS_FINISH;

            if (_status == STA_READY)
            {

                DoEnter(input);
                _needExit = true;
                _status = STA_RUNNING;
            }

            if (_status == STA_RUNNING)
            {
                isFinish = DoExecute(input, output);
                if (isFinish == BRS_FINISH || isFinish < 0)

                    _status = STA_FINISH;
            }

            if (_status == STA_FINISH)
            {
                if (_needExit)

                    DoExit(input, isFinish);

                _status = STA_READY;
                _needExit = false;
            }

            return isFinish;
        }

        protected override void DoTransition(BevNodeInputParam input)
        {
            if (_needExit)

                DoExit(input, BRS_ERROR_TRANSITION);

            _status = STA_READY;
            _needExit = false;
        }

        protected void DoEnter(BevNodeInputParam input)
        {
            // nothing to do...implement yourself
        }

        protected int DoExecute(BevNodeInputParam input, BevNodeOutputParam output)
        {
            return BRS_FINISH;
        }

        protected void DoExit(BevNodeInputParam input, int exitID)
        {
            // nothing to do...implement yourself
        }
    }
}
